<template>
  <receipt-table
    :url="url"
    :submit-form="submitForm"
    :search-form="searchForm"
    :submit-form-title="props.receiptsType"
    :edit-btn-visible="props.editBtnVisible"
    submit-form-width="80%"
    :detail-btn-visible="true"
    :detail-form-dialog="{ title: '单据', width: '800px' }"
    :approve-name="props.approveName"
    @data-format="dataFormat"
    @set-form-init-value="setFormInitValue"
    @submit-valid="submitValid"
    @json-format="submitJsonFormat"
  >
    <template #submitForm>
      <el-form
        :model="submitForm"
        :rules="formRules"
        :label-width="100"
        ref="submitFormRef"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="内部编码：" prop="no" label-width="120px">
              <el-input v-model="submitForm.no" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手写编号：" prop="noHand" label-width="120px">
              <el-input v-model="submitForm.noHand"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名称：" prop="name" label-width="120px">
              <el-input v-model="submitForm.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <slot name="idJsonSlot"></slot>
        <el-form-item label="备注：" prop="remark" label-width="120px">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="submitForm.remark"
          ></el-input>
        </el-form-item>
        <el-row>
          <el-form-item label="详情：" style="width: 100%">
            <el-table :data="submitForm.receiptsSub" max-height="400px">
              <el-table-column
                align="center"
                type="index"
                prop="no"
                label="序号"
                fixed="left"
                width="60"
                min-width="60"
              />
              <el-table-column
                align="center"
                prop="subNo"
                label="项目编号"
                width="180"
                min-width="160"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.subNo"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="subName"
                label="名称"
                width="180"
                min-width="180"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.subName"></el-input>
                </template>
              </el-table-column>
              <!--subJson的插槽，展示subJson内的内容-->
              <slot name="subJson"></slot>
              <el-table-column
                align="center"
                prop="remark"
                label="备注"
                min-width="220"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.remark"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="操作"
                fixed="right"
                fit
                width="80"
                min-width="60"
              >
                <template #default="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="delete"
                    @click="deleteRowSub(scope.$index)"
                    >删除
                  </el-button>
                  <template v-if="props.openDetailsSubVisible">
                    <el-button
                      type="text"
                      size="small"
                      icon="ArrowRightBold"
                      @click="openDetailsSub(scope.$index, submitForm.no)"
                      >展开
                    </el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-button type="primary" plain @click="addRowSub">增加</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template #subDetails>
      <el-form
        :model="submitForm"
        :rules="formRules"
        :label-width="100"
        ref="submitFormRef"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单手写编号：" label-width="120px">
              <el-input v-model="submitForm.noHand" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名称：" label-width="120px">
              <el-input v-model="submitForm.name" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目编号：" label-width="120px">
              <el-input v-model="itemNo" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--subJson的插槽，提取subJson内的内容放在最上方仅展示-->
        <slot name="subJsonDetails"></slot>
        <el-row>
          <el-form-item label="BOM：" style="width: 100%">
            <!--subJson的插槽，提取subJson内的内容放在最上方仅展示-->
            <slot name="subJsonDetailsTable"></slot>
          </el-form-item>
        </el-row>
      </el-form>
    </template>

    <template #searchForm>
      <el-form :model="searchForm" :label-width="100">
        <el-form-item label="状态：">
          <el-select v-model="searchForm.invalid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内部编码：">
          <el-input v-model="searchForm.no"></el-input>
        </el-form-item>
        <el-form-item label="手写编码：">
          <el-input v-model="searchForm.noHand"></el-input>
        </el-form-item>
        <el-form-item label="名称：">
          <el-input v-model="searchForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="searchForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="创建人：">
          <el-input v-model="searchForm.createUser"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建时间始：">
              <el-date-picker
                v-model="searchForm.createGmtStart"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间止：">
              <el-date-picker
                v-model="searchForm.createGmtEnd"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="修改人：">
          <el-input v-model="searchForm.modifiedUser"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="修改时间始：">
              <el-date-picker
                v-model="searchForm.modifiedGmtStart"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间止：">
              <el-date-picker
                v-model="searchForm.modifiedGmtEnd"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
  </receipt-table>
</template>

<script lang="ts" setup>
import ReceiptTable from "@/components/receipt/ReceiptTable.vue";
import { TableUrl } from "@/models/TableSetting";
import {
  defineEmits,
  defineProps,
  inject,
  provide,
  ref,
  withDefaults,
} from "vue";
import { Receipts } from "@/models/Receipts";
import api from "@/utils";
import { AxiosResponse } from "axios";
import { ReceiptsSub } from "@/models/ReceiptsSub";
import { ElMessage, ElMessageBox } from "element-plus";
import OrderReceiptSubDetails from "@/components/receipt/OrderReceiptSubDetails";

const props = withDefaults(defineProps<ReceiptsProps>(), {
  receiptsName: "",
  receiptsNo: "",
  receiptsType: "",
  approveName: "",
  openDetailsSubVisible: false,
  editBtnVisible: true,
});

export interface ReceiptsProps {
  receiptsName: string;
  receiptsNo: string;
  receiptsType: string;
  approveName: string;
  openDetailsSubVisible?: boolean;
  editBtnVisible?: boolean;
}

const url = {
  refreshUrl: "/receipts/" + props.receiptsName,
  modifyingSingleUrl: "/receipts/" + props.receiptsName,
  deleteUrl: "/receipts/" + props.receiptsName + "/batchDelete",
  invalidUrl: "/receipts/" + props.receiptsName + "/batchInvalid",
  searchUrl: "/receipts/" + props.receiptsName + "/search",
  approveUrl:
    "/receipts/" + props.receiptsName + "/approve/" + props.approveName,
  submitApproveUrl:
    "/receipts/" + props.receiptsName + "/submitApprove/" + props.approveName,
} as TableUrl;

// 校验规则
const formRules = {
  noHand: [
    {
      required: true,
      message: "编号不能为空",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "单据名不能为空",
      trigger: "blur",
    },
  ],
};
//选择器
const options = [
  {
    value: "正常",
    label: "正常",
  },
  {
    value: "作废",
    label: "作废",
  },
];

// 申明表单
const submitFormRef = ref();
const submitForm = ref({} as Receipts);
const searchForm = ref({} as Receipts);
const subOpenIndex = ref(0 as number);
const receiveIdJsonItems = inject("idJsonItems");

const emit = defineEmits<{
  (e: "clear-open-json"): void;
  (e: "add-row-sub"): void;
  (e: "delete-row-sub", index: number): void;
  (e: "pose-edit-json", idJson: unknown, receiptsSub?: Array<unknown>): void;
  (
    e: "pose-sub-details-edit-json",
    subJsonRow: unknown,
    no: string,
    itemNo: string
  ): void;
  (
    e: "pose-submit-json",
    callback: (value: Array<ReceiptsSub>) => void,
    no: string,
    receiptsSub?: Array<unknown>
  ): void;
  (
    e: "data-format",
    columnName: string,
    cellValue: string,
    callback: (value: string) => void
  ): void;
  (
    e: "json-format",
    data: Record<string, unknown>[][],
    callback: (value: Record<string, unknown>[]) => void
  ): void;
}>();

// 数据规范, 表中没有需要规范格式的数据, 则不需要这一行.
const dataFormat = (
  columnName: string,
  cellValue: string,
  callback: (value: string) => void
) => {
  emit("data-format", columnName, cellValue, (value: string) => {
    cellValue = value;
  });
  callback(cellValue);
};

const setFormInitValue = async (formType: string, row: Receipts) => {
  if (undefined !== submitFormRef.value) {
    submitFormRef.value.clearValidate();
  }
  switch (formType) {
    case "insert":
      submitForm.value = {
        no: "",
        name: "",
        remark: "",
        createUser: sessionStorage.getItem("token") as string,
        createGmt: new Date(),
        modifiedUser: sessionStorage.getItem("token") as string,
        modifiedGmt: new Date(),
        receiptsSub: [{}],
      } as Receipts;
      emit("clear-open-json");
      getReceiptsNO(
        props.receiptsNo,
        sessionStorage.getItem("userNo") as string
      );
      submitForm.value.receiptsType = props.receiptsType;
      break;
    case "update":
      submitForm.value = row;
      emit(
        "pose-edit-json",
        submitForm.value.idJson,
        submitForm.value.receiptsSub
      );
      submitForm.value.modifiedUser = sessionStorage.getItem("token") as string;
      submitForm.value.modifiedGmt = new Date();
      break;
  }
};

/**
 * 提交数据前的校验
 * @param callback 回调函数,将校验结果返还到Table组件中.
 */
const submitValid = (callback: (value: boolean) => void) => {
  submitForm.value.idJson = receiveIdJsonItems;
  emit(
    "pose-submit-json",
    (value: Array<ReceiptsSub>) => {
      submitForm.value.receiptsSub = value;
    },
    submitForm.value.no,
    submitForm.value.receiptsSub
  );
  submitFormRef.value
    .validate()
    .then(() => {
      callback(true);
    })
    .catch(() => {
      callback(false);
    });
};

const lastReceiptsNo = ref("");
const lastUserNo = ref("");
const getReceiptsNO = async (receiptsNo?: string, userNo?: string) => {
  if (receiptsNo === null || receiptsNo === undefined) {
    receiptsNo = lastReceiptsNo.value;
  }
  if (userNo === null || userNo === undefined) {
    userNo = lastUserNo.value;
  }
  const date = new Date();
  const dateFormat = api.formatDate(date, "yyyyMM");
  let returnNO = "";
  await api.http
    .get(
      "/receipts/" +
        props.receiptsName +
        "/generateReceiptsNo/" +
        receiptsNo +
        userNo +
        dateFormat
    )
    .then((res: AxiosResponse) => {
      console.log(res);
      returnNO = res.data;
      submitForm.value.no = returnNO;
      lastReceiptsNo.value = receiptsNo as string;
      lastUserNo.value = userNo as string;
    })
    .catch((err: string) => {
      console.log(err);
    });
};
provide("getReceiptsNO", getReceiptsNO);
//增加和删除某行
const addRowSub = () => {
  submitForm.value.receiptsSub?.push({ no: submitForm.value.no });
  emit("add-row-sub");
};
const deleteRowSub = (index: number) => {
  ElMessageBox.confirm("确认删除本行记录吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (submitForm.value.receiptsSub.length > 1) {
      submitForm.value.receiptsSub?.splice(index, 1);
      emit("delete-row-sub", index);
    } else {
      ElMessage({
        message: "已经不能再少了",
        type: "warning",
      });
    }
  });
};

// 子表sub详情ts文件引入
const { changeOrderReceiptSubDetailsDialogVisibleValue } =
  OrderReceiptSubDetails();
//BOM展开
const itemNo = ref("" as string);
const openDetailsSub = (index: number, no: string) => {
  subOpenIndex.value = index;
  if (
    submitForm.value.receiptsSub[subOpenIndex.value].subNo === undefined ||
    submitForm.value.receiptsSub[subOpenIndex.value].subNo === "" ||
    submitForm.value.receiptsSub[subOpenIndex.value].subNo === null
  ) {
    ElMessage({
      message: "请给此项目一个项目编号",
      type: "warning",
    });
  } else {
    itemNo.value = submitForm.value.receiptsSub[subOpenIndex.value]
      .subNo as string;
    emit(
      "pose-sub-details-edit-json",
      submitForm.value.receiptsSub[subOpenIndex.value].subJson,
      no,
      itemNo.value
    );
    changeOrderReceiptSubDetailsDialogVisibleValue();
  }
};
//上传
const submitJsonFormat = (
  data: Record<string, unknown>[][],
  callback: (value: Record<string, unknown>[]) => void
) => {
  let newValue: Record<string, unknown>[] = [];
  emit("json-format", data, (value: Record<string, unknown>[]) => {
    newValue = value;
  });
  callback(newValue);
};
// 控制编辑、提交、审批按钮显示
const isSubmitVisible = (approveStatus: string) => {
  const submitVisible = inject("submitVisible");
  return approveStatus === submitVisible;
};
provide("isSubmitVisible", isSubmitVisible);

const isApproveVisible = (approveStatus: string) => {
  const approveVisible = inject("approveVisible");
  return approveStatus === approveVisible;
};
provide("isApproveVisible", isApproveVisible);

const isEditVisible = (approveStatus: string) => {
  const editVisible = inject("editVisible");

  return approveStatus === editVisible;
};
provide("isEditVisible", isEditVisible);
</script>

<style scoped></style>
